/*******************************************************************************
 *            SHOPPING CART COLLECTIONS CLASS EXTENDS COLLECTION CLASS
 ******************************************************************************/
function CartCollection() {};
//inherit from Collection class
CartCollection.prototype = new Collection();
//reset the contructor after inheritance
CartCollection.prototype.constructor = CartCollection;

//augmenting the prototype


CartCollection.prototype.getTotalCost = function() {
    var self = this;
    var grand_total = 0
    self.iterate(function(key,obj){
        var amt = obj.amount;
        grand_total = grand_total + amt;
    });
    return grand_total;
}

/*******************************************************************************
 *            END OF SHOPPING CART COLLECTIONS CLASS
 ******************************************************************************/


var Student = {
    _cart: new CartCollection(),
    selected_ui_cart:{},

    init:function () {
        var self = this;

        self._cart.registerCallback('add', function(key, obj) {
            self.hideAndShowNavButton();
            //self.updateCartUi();
        });

        self._cart.registerCallback('remove', function(key) {
            self.hideAndShowNavButton();
            //self.updateCartUi();
        });

        $("#cart_carousel").carousel({
            interval: '6000000'
        })


        $(".btn.next").click(function() {
            var btn = $(".btn.next");
            var btn_prev =  $(".btn.prev");
            var visible = $('#fees-cart').is(':visible');
            if(visible){//stop the cycling and do complete payment
                self.doPayment(btn,btn_prev);
                return;
            }
            var items = self._cart.getSize();
            if(items > 0){
                self.updateCartUi();
                $(".btn.prev").show();
                btn.html('Complete Payment');
                self.updatetTotalToPay(self.selected_ui_cart);
                $(".nano").nanoScroller();
                $("#cart_carousel").carousel('next');
                $("#cart_carousel").carousel('pause');
            }
        });

        $(".btn.prev").click(function() {
            var visible = $('#fees-items').is(':visible');
            if(visible){
                return; //stop the cycling
            }
            $(".btn.next").html('Next &raquo;')
            self.updatetTotalToPay(global_cart_item);
            $("#cart_carousel").carousel('prev');
            $("#cart_carousel").carousel('pause');
            $(".btn.prev").hide();
        });

        $(".nano").nanoScroller();


        //bind select item button for toggle
        $('#fees-items ul li button').click(function(){
            var btn = $(this);
            if(btn.hasClass('btn-info')){//already selected, now unselect it and remove from collection
                btn.removeClass('btn-info').html("<i class='icon-info-sign'></i>  Select &nbsp;&nbsp;&nbsp;")
                //remove from collection
                self._cart.remove(btn.attr('data-id'));
            }
            else{//select it and add to collection
                btn.addClass('btn-info').html("<i class='icon-check'></i> Selected");
                //add to collection
                self._cart.add(btn.attr('data-id'),{
                    id:global_cart_item[btn.attr('data-id')]['id'],
                    fee_type_id:global_cart_item[btn.attr('data-id')]['fee_type_id'],
                    fee_category:global_cart_item[btn.attr('data-id')]['fee_category'],
                    class:global_cart_item[btn.attr('data-id')]['class'],
                    description:global_cart_item[btn.attr('data-id')]['description'],
                    trans_type_to_use:global_cart_item[btn.attr('data-id')]['trans_type_to_use'],
                    amount:global_cart_item[btn.attr('data-id')]['amount'],
                    paid:global_cart_item[btn.attr('data-id')]['paid'],
                    owed:global_cart_item[btn.attr('data-id')]['owed'],
                    button:global_cart_item[btn.attr('data-id')]['button']
                })
            }
        });


        //bind remove button for for removing items from cart
        $('#fees-cart ul li button').live('click',function(){
            var btn1 = $(this);
            //find selected button on slide one  with the data-id value and unselect it
            var id = btn1.attr('data-id');
            $('#fees-items ul li button').each(function(){
                var btn = $(this);
                if(btn.attr('data-id') == id){
                    btn.click();
                    btn1.parents('li').remove();
                }
            });
        });

        self.hideAndShowNavButton();
        self.updatetTotalToPay(global_cart_item);

       /* $('#fees-cart ul li span input').live('keypress',function(event) {
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        });*/

        $('#fees-cart ul li span input').live('keydown',function(event) {
            //console.log('key code '+event.keyCode)
            //console.log('key which '+event.which)
            //console.log(typeof event.which)
            if(event.which == 8 || event.which == 37 || event.which == 40 || event.which == 38 || event.which == 39){
                //allow keys for backspace, arrow keys
            }
            else{
                if ((event.which != 190 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                    //console.log('prevent')
                    event.preventDefault();
                }
            }
        });
    },


    hideAndShowNavButton: function(){
        var self = this;
        var items = self._cart.getSize();
        var visible = $('#fees-items').is(':visible');
        //console.log(visible);
        if(items > 0){
            $(".btn.next").show();
            if(!visible){
                $(".btn.prev").show();
            }
        }
        else{
            $(".btn.next").hide();
            $(".btn.prev").hide();
            $(".btn.next").html('Next &raquo;');
            $("#cart_carousel").carousel(0);
        }
    },

    updateCartUi: function(){
        var self = this;
        var cat_arr = {};
        self.selected_ui_cart = [];
        self._cart.iterate(function(key,obj){
            //the headers
            if(typeof cat_arr[obj.fee_category] == 'undefined'){

                cat_arr[obj.fee_category] = obj.fee_category;
                if(global_cart_item[obj.fee_category].paid == 'PAID'){
                    global_cart_item[obj.fee_category].paid = 'PAYING';
                }
                //self.selected_ui_cart[''+obj.fee_category+''] = global_cart_item[obj.fee_category];
                self.selected_ui_cart.push(global_cart_item[obj.fee_category]);
            }

            //self.selected_ui_cart[key] = obj;
            self.selected_ui_cart.push(obj);
        });
        //Now display them
        var str = '';
        for(var x in self.selected_ui_cart){
            var $value = self.selected_ui_cart[x];
            var $class = $value['class'];
            str+="<li class='"+$class+"'>";
            str+=$value['description'];
            var $style = 'margin-right: 100px;';
            if($value['button'] == 'y'){
                $style = "";
                str+="<button class='btn btn-danger btn-mini pull-right' data-id='"+$value['id']+"'  data-use='"+$value['trans_type_to_use']+"' ><i class='icon-remove'></i>  Remove</button>";
            }
            str+="<span class='pull-right amounts' style='"+$style+"'>";
                if($value['class'] == 'nav-header'){
                    str+="<span class='currency'></span>";
                    str+="<span class='amount'>"+$value['amount']+"</span>";
                    str+="<span class='owed'>"+$value['owed']+"</span>";
                }
                else{
                    str+="<span class='currency'>GHc</span>";
                    str+="<span class='amount'>"+$value['amount']+"</span>";
                    str+="<span class='owed'>"+$value['owed']+"</span>";
                }
                if($value['button'] == 'y'){
                    str+="<span class='paid'><input type='text' class='input-mini' data-owed='"+$value['owed']+"' value='"+$value['owed']+"' /></span>";
                }
                else{
                    str+="<span class='paid'>"+$value['paid']+"</span>";
                }
            str+="</span>";
            str+="</li>";
        }
        $('#fees-cart ul.nav-list').html('');
        $('#fees-cart ul.nav-list').html(str);
    },

    doPayment:function(btn,btn_prev){
        var self = this;
        //Hide the button to prevent double clicks
        btn.hide();
        btn_prev.hide();
        var r=window.confirm("Are you sure you want to make payment ?");
        if (r){
            var saveData = {};
            $('#fees-cart ul li span input').each(function(){
                var txt = $(this);
                var btn =  txt.parents('li').find('button');
                var fee_id =btn.attr('data-id');
                var trans_use = btn.attr('data-use');
                var feeObject = self._cart.get(fee_id);
                if(isFinite(txt.val())){
                    saveData[fee_id] = {'amount':txt.val(),'trans_type_to_use':trans_use};
                }
                else{
                    saveData[fee_id] = {'amount':0.00,'trans_type_to_use':trans_use};
                }
                if(feeObject){
                    saveData[fee_id]['fee_type_id'] = feeObject.fee_type_id;
                }
            });

            var res = self.validatePayment(saveData);
            //console.log(saveData);
            if(res.status){
                self.submitForm(saveData,btn,btn_prev);
                //console.log('paying....')
            }
            else{
                btn.show();
                btn_prev.show();
                var txt = '';
                for (var x in res.msg) {
                    txt += res.msg[x] + '\r';
                }
                alert(txt);
            }
        }
        else{
            btn.show();
            btn_prev.show();
        }
    },

    getTotalToPay:function(arr){
        var self = this;
        var total = 0.00;
        for(var x in arr){
            var $value = arr[x];
            if(isFinite($value['owed'])){
                total = total + parseFloat($value['owed']);
            }
        }
        return total;
    },

    updatetTotalToPay:function(arr){
        var self = this;
        var t = self.getTotalToPay(arr);
        $('#total_amt_topay').html(jLib.formatNumber(t,'money'));
    },

    validatePayment:function(saveData){
        var self = this;

        var $return = {
            'status':true,
            'msg':[]
        };

        var tl_paying = 0.00;
        var acct_balance  = parseFloat($('#acct_balance').val());
        for(var x in saveData){
            var pay = parseFloat(saveData[x]['amount']);
            tl_paying = tl_paying + pay;
            /*if(typeof self.selected_ui_cart[x] != 'undefined'){
                //console.log(self.selected_ui_cart[x]);
                //check if they are overpaying for individual fee
                if(pay <= parseFloat(self.selected_ui_cart[x].owed)){

                }
                else{
                    $return['status'] = false;
                    $return['msg'].push("You can't over pay for "+self.selected_ui_cart[x].description);
                }
            }*/
        }

        var selected_tl_owed = 0.00;
        for(var x in self.selected_ui_cart){
            var $value = self.selected_ui_cart[x];
            if(isFinite($value['owed'])){
                selected_tl_owed = selected_tl_owed + parseFloat($value['owed']);
            }
        }

        //Check if Amount paying is more than Credit amount
        if(acct_balance >= tl_paying ){

        }
        else{
            $return['status'] = false;
            $return['msg'].push("You don't have enough credit for this payment.");
        }

        //console.log('total paying '+tl_paying);
        //console.log('total owing '+selected_tl_owed);
        //Check if the student is overpaying
        if(tl_paying <= selected_tl_owed ){

        }
        else{
            /*$return['status'] = false;
            $return['msg'].push("You can't over pay your fees.");*/
        }

        return $return;
    },

    /*
     * AJAX login
     * This function will handle the login process through AJAX
     */
    submitForm:function (data,btn,btn_prev) {
        var self = this;
        var query = 'data=' + encodeURIComponent(JSON.stringify(data));
        //var query = 'data=' + JSON.stringify(data);
        var url = $('#do-payment-url').val();
        /* Send the data to the server and handle the server response */
        $.ajax({
            url: url,
            data: query,
            dataType: 'json',
            type: 'POST',
            success:function(response) {
                var txt = '';
                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '\r';
                    }
                }
                else {
                    txt = response.mesg
                }
                /* When everything went on smoothly on the server redirect the user to the appropriate page.*/
                if (response.code === 0) {
                    // Show progress
                    window.location = $('#payment-url').val();
                }
                /* When there are Errors */
                else if (response.code === 1) {
                    btn.show();
                    btn_prev.show();
                    alert(txt);
                }
            },
            error: function(xhr) {
                btn.show();
                btn_prev.show();
                console.log(xhr.responseText);
            }
        });
    }
};

/* when the page is loaded */
$(document).ready(function () {
    Student.init();
});